package cn.gov.pbc.gd.credit.log;


import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.liu.jbase.BaseVo;
import com.liu.jbase.PageListVo;
import com.liu.jbase.ResultVo;
import com.liu.jbase.constant.ResCode;
import com.liu.jbase.util.AnnotationUtil;
import com.liu.tools.NetHelper;
import com.liu.tools.StrUtil;
import com.liu.tools.conf.ConfigurerEx;

import cn.gov.pbc.gd.credit.common.model.UserModel;
import cn.gov.pbc.gd.credit.common.service.redis.IRedisService;
import cn.gov.pbc.gd.credit.common.util.UserUtil;

/**
 * @date 2017年5月4日
 * @time 下午3:35:31
 * @author liuxingmi
 * @desc 拦截器
 */
@Component
@Aspect
@Order(value = Ordered.HIGHEST_PRECEDENCE + 10)
public class ServiceAspect {
	
	@Autowired
	private IRedisService redisService;
	
	private static Logger logger = LoggerFactory.getLogger(ServiceAspect.class);
	
	// 匹配  包下所有类的所有方法作为切入点  
    @Around("(execution(* cn.gov.pbc.gd.credit.*.service..*.impl..*Impl.*(..)) || execution(* com.liu.jbase.service.impl..*Impl.*(..))) && !execution(* cn.gov.pbc.gd.credit.common.service..*(..))")  
    public Object around(ProceedingJoinPoint jp) throws java.lang.Throwable {  
        
    	long st = System.currentTimeMillis();
    	
    	String methodName = jp.getSignature().getName();
    	String methodPath = jp.getTarget().getClass() + ":" + methodName;
    	logger.debug("ServiceAspect:around msg=" + methodPath + "触发业务公用拦截器！");
       
   	    // 获取request
    	HttpServletRequest request = null;
    	if(RequestContextHolder.getRequestAttributes() != null){
    		
    		request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    	    	
	        String sessionId = request.getParameter("sid");
	      
	        Object params[] = jp.getArgs();
	        
	        for (Object object : params) {
	            if (object instanceof BaseVo) {
	            	
	            	 UserModel userModel = UserUtil.getUserModel(sessionId, redisService);
	            	 BaseVo baseVo = (BaseVo) object;
	            	 baseVo.setSid(sessionId);
	            	 baseVo.setIp(NetHelper.getIpAddr(request));
		
		             if (userModel != null) {
		            	 
		            	 if("add".equals(methodName) || "update".equals(methodName)){
			                 // 判断当前对象是否有userId属性
		            		 
		            		 AnnotationUtil.getInstance().setFieldValue(object, "userId", userModel.getUserId(), false);
			                 
			                 AnnotationUtil.getInstance().setFieldValue(object, "createBy", userModel.getUserId(), false);
			                 AnnotationUtil.getInstance().setFieldValue(object, "updateBy", userModel.getUserId(), false);
			                 AnnotationUtil.getInstance().setFieldValue(object, "updateTime", new Date(), false);
			                 AnnotationUtil.getInstance().setFieldValue(object, "createTime", new Date(), false);
	
		            	 }
		             }
	                
	            }
	            
	            if (object instanceof PageListVo) {
	            	
	                PageListVo<?> pageListVo = (PageListVo<?>) object;
	               
	                Object page = request.getParameter("curPage");
	                if (page != null) {
	                    pageListVo.setCurrPage(Integer.parseInt(page.toString()));
	                }
	                Object pageSize = request.getParameter("pageSize");
	                if (pageSize != null) {
	                    pageListVo.setPageSize(Integer.parseInt(pageSize.toString()));
	                }
	            }
	         }
    	} 
        Object object = null;
    	if(jp.getArgs().length != 0){
        
	    	object = jp.getArgs()[0];  
	
	        String jsonStr = JSON.toJSONString(object);        
	        
	        logger.debug("ServiceAspect:around msg=" + methodPath + "  请求参数信息：" + jsonStr);
	        	        
    	}
    	
        Object rvt = jp.proceed();
        if(rvt == null){
        	return new ResultVo<>();
        }
        ResultVo<?> resultDto = (ResultVo<?>) rvt;
        
        if(! ResCode.SUCCESS.equals(resultDto.getCode()) && StrUtil.isNull(resultDto.getMsg())){
        	resultDto.setMsg(ConfigurerEx.getProperty(resultDto.getCode(), "未知问题"));
        }
        
        logger.info("ServiceAspect:around msg=" + methodPath	+ " 业务方法执行时间：" + (System.currentTimeMillis() - st) + "ms");
        logger.debug("ServiceAspect:around msg=" + methodPath	+ " 业务返回内容：" + JSON.toJSONString(rvt));
        
        return resultDto;  
    } 
        
}
